<template>
  <div class="container" v-if="createAuth">
    <!-- 头部 -->
    <page-header
      :title="
        $route.query.id
          ? $t('m.Modify_advertisements')
          : $t('m.Upload_advertisement_file')
      "
      :has-return="true"
    >
    </page-header>

    <!-- 节目单信息 -->
    <div class="table_top">
      <div class="top">
        <div class="top_box">
          <div
            v-for="(item, index) in imgTypeList"
            :key="index"
            :class="{ active: imgTypeIndex == item.value }"
            @click="imgTypeIndex = item.value"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
      <div class="top_img" :class="{ actives: imgTypeIndex == 2 }">
        <div
          class="top_img_div"
          v-for="item in imgTypeList[imgTypeIndex - 1].list"
          :key="item.value"
        >
          <div class="img_div">
            <img :src="item.backgroundImg" alt="" />
          </div>
          <div class="img_text">
            {{ item.label }}
          </div>
        </div>
      </div>
      <div class="top_dot">
        <span
          style="margin-right:3px;"
          :class="{ active1: imgTypeIndex == 1 }"
          @click="imgTypeIndex = 1"
        ></span>
        <span
          :class="{ active1: imgTypeIndex == 2 }"
          @click="imgTypeIndex = 2"
        ></span>
      </div>
      <el-divider class="el_divider"></el-divider>
      <div class="el_dialog_center" style="padding:20px 0;">
        <div
          v-if="dialogType == 1"
          class="el_dialog_title1"
          style="font-size:14px;line-height:16px;font-weight:500;"
        >
          {{ $t('m.Select_group') }}*
        </div>
        <div v-if="dialogType == 1">
          <el-select v-model="adsDetail.groupId" style="width:476px;">
            <el-option
              v-for="item in options4"
              :key="item.value"
              :label="item.defaulted ? $t('m.All_advertisements') : item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div
          v-if="dialogType == 2"
          class="el_dialog_title1"
          style="font-size:14px;line-height:16px;font-weight:500;"
        >
          {{ $t('m.Program_titles') }}*
        </div>
        <el-form
          v-if="dialogType == 2"
          class="el_form_upload"
          :model="adsDetail"
          :rules="rules2"
          ref="adsDetail"
        >
          <el-form-item prop="title">
            <el-input
              class="el_input"
              v-model="adsDetail.title"
              maxlength="50"
              style="width:476px;"
              :placeholder="$t('m.Please_enter')"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <div class="el_uploaded2">
              <div class="el_uploaded_img">
                <el-image
                  v-if="adsDetail.fileType == 1"
                  :src="
                    playType == 1 ? fileUrlFormat(adsDetail.url) : adsDetail.url
                  "
                  :preview-src-list="[
                    playType == 1 ? fileUrlFormat(adsDetail.url) : adsDetail.url
                  ]"
                  alt=""
                  class="image_vertical"
                  fit="cover"
                />
                <video
                  v-else
                  :src="
                    playType == 1 ? fileUrlFormat(adsDetail.url) : adsDetail.url
                  "
                  class="image_vertical"
                ></video>
                <img
                  src="@/assets/imgs/ic_play@2x.png"
                  alt=""
                  class="video_img"
                  v-show="adsDetail.fileType == 2"
                  @click="playVideo(adsDetail.url)"
                />
              </div>
              <div class="el_uploaded_right">
                <el-upload
                  ref="upload"
                  :action="'/manage/adverts/update'"
                  :data="{
                    groupId: adsDetail.groupId,
                    id: adsDetail.id,
                    title: adsDetail.title
                  }"
                  :headers="platformId"
                  :on-change="changeList"
                  :on-success="onSuccess2"
                  :on-error="onError2"
                  :before-upload="beforeUpload2"
                  name="files"
                  :show-file-list="false"
                  :auto-upload="false"
                  :file-list="fileList"
                  :accept="
                    adsDetail.fileType == 1
                      ? 'image/jpeg,image/png,image/webp'
                      : 'video/mp4'
                  "
                >
                  <el-button class="el_button" @click="uploadBtn">{{
                    $t('m.Replace_file')
                  }}</el-button>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <el-upload
          class="el_upload el_upload2"
          drag
          action="/manage/adverts/files/upload"
          name="files"
          :on-change="handleChange"
          :on-success="onSuccess"
          :on-error="onError"
          :before-upload="beforeUpload"
          :headers="platformId"
          :multiple="true"
          :data="{ groupId: adsDetail.groupId }"
          :show-file-list="false"
          :file-list="fileList"
          v-if="dialogType == 1"
        >
          <div>
            <img
              src="@/assets/imgs/ic_add.svg"
              alt=""
              class="el_upload_img"
              style="margin-top:30px"
            />
            <div class="el_upload_title">
              {{ $t('m.Upload_files_text') }}
            </div>
          </div>
        </el-upload>
        <div
          class="el_dialog_center_bottom"
          :style="dialogType == 1 ? 'margin-bottom:8px;' : ''"
          v-show="
            dialogType == 1 || (dialogType == 2 && adsDetail.fileType == 2)
          "
        >
          {{ $t('m.Upload_video_text') }}
        </div>
        <div
          class="el_dialog_center_bottom"
          v-show="
            dialogType == 1 || (dialogType == 2 && adsDetail.fileType == 1)
          "
        >
          {{ $t('m.Upload_img_text') }}
        </div>
      </div>
      <el-divider class="el_divider" v-if="dialogType == 2"></el-divider>
      <div v-if="dialogType == 2" style="padding: 16px 0 0;text-align: right;">
        <span slot="footer" class="dialog-footer">
          <el-button @click="editAds()" class="cancel_btn confirm_btn">{{
            $t('m.save')
          }}</el-button>
        </span>
      </div>
    </div>

    <!-- 查看视频 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="playDialog"
      :title="$t('m.play_video')"
      width="640px"
      append-to-body
      @close="closePlay"
    >
      <div class="el_dialog_center">
        <video
          :src="fileUrlFormat(urlVideo)"
          controls="controls"
          autoplay="autoplay"
          class="play_video"
        ></video>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      fileList: [],
      options4: [],
      dialogType: 1,
      adsDetail: {
        fileType: '', //	文件类型：1-图片 2-视频
        groupId: '', //	组ID
        id: null, //	主键id
        title: '', //	标题
        url: ''
      },
      rules2: {
        title: [
          {
            required: true,
            message: this.$t('m.This_field_required'),
            trigger: 'blur'
          }
        ]
      },
      platformId: {
        'platform-id': parseInt(
          (this.$cache.get('platformId'))
        ),
        add: this.$cache.getLang(),
        'brezze-language':
          this.$cache.getLang() == 'CN' ? 'ZH' : this.$cache.getLang()
      }, //导入请求头
      playType: 1,
      urlVideo: '',
      playDialog: false,
      imgTypeList: [
        {
          value: 1,
          label: this.$t('m.Table_top_screen_resolution'),
          list: [
            {
              value: 1,
              backgroundImg: require('@/assets/imgs/work/1280_800@2x.png'),
              label: this.$t('m.Horizontal_full_screen_resolution')
            },
            {
              value: 2,
              backgroundImg: require('@/assets/imgs/work/800_1280@2x.png'),
              label: this.$t('m.Vertical_full_screen_resolution4')
            },
            {
              value: 3,
              backgroundImg: require('@/assets/imgs/work/800_864@2x.png'),
              label: this.$t('m.Vertical_screen_partition_resolution4')
            }
          ]
        },
        {
          value: 2,
          label: this.$t('m.Standee_screen_resolution'),
          list: [
            {
              value: 4,
              backgroundImg: require('@/assets/imgs/work/1080_1920@2x.png'),
              label: this.$t('m.Vertical_full_screen_resolution24')
            },
            {
              value: 5,
              backgroundImg: require('@/assets/imgs/work/1080_1440@2x.png'),
              label: this.$t('m.Vertical_screen_partition_resolution24')
            }
          ]
        }
      ],
      imgTypeIndex: 1,
      createAuth: this.permissionsId(208)
    }
  },
  created () {
    if (!this.createAuth) {
      return
    }
    this.getOption()
    if (this.$route.query.id) {
      this.getDetail()
    }
  },
  methods: {
    //广告组-下拉选项
    getOption () {
      this.$api.ad.optionADsGroup().then(res => {
        if (res.code == 0) {
          this.options4 = res.data
          this.adsDetail.groupId = res.data[0].value
        }
      })
    },
    //获取详情
    getDetail () {
      this.$api.ad.getAdDetail(this.$route.query.id).then(res => {
        if (res.code == 0) {
          this.adsDetail = res.data
          this.dialogType = 2
          this.fileList = []
          this.$nextTick(() => {
            this.$refs['adsDetail'].clearValidate(['title'])
          })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //文件状态改变
    handleChange (file, fileList) {
      // this.fileList = fileList
    },

    //上传成功回调
    onSuccess (res, file, fileList) {
      this.$closeLoading()
      let resData = res
      this.$message({
        type: resData.code == '0' ? 'success' : 'error',
        message: resData.message
      })
      this.$router.push({ path: '/ads/program' })
    },

    //上传失败
    onError (res, file, fileList) {
      this.$closeLoading()
    },
    onError2 (res, file, fileList) {
      this.$closeLoading()
    },

    //上传广告前限制
    beforeUpload (file) {
      // console.log(file)
      const isLt20M = file.size / 1024 / 1024 < 20
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/webp' ||
        file.type === 'image/png' ||
        file.type === 'video/mp4'
      if (!isLt20M) {
        setTimeout(() => {
          this.$notify({
            title: file.name + ' ' + this.$t('m.Upload_failed'),
            message: this.$t('m.File_size_mb'),
            type: 'warning',
            duration: 3000
          })
        }, 0)
        return false
      }
      if (!isJPG) {
        setTimeout(() => {
          this.$notify({
            title: file.name + ' ' + this.$t('m.Upload_failed'),
            message: this.$t('m.Incorrect_file_format'),
            type: 'warning',
            duration: 3000
          })
        }, 0)
        return false
      }
      this.$openLoading()
      return true
    },
    //上传广告前限制
    beforeUpload2 (file) {
      // console.log(file)
      const isLt20M = file.size / 1024 / 1024 < 20
      const isJPG1 =
        file.type === 'image/jpeg' ||
        file.type === 'image/webp' ||
        file.type === 'image/png'
      const isJPG2 = file.type === 'video/mp4'
      if (!isLt20M) {
        setTimeout(() => {
          this.$notify({
            title: file.name + ' ' + this.$t('m.Upload_failed'),
            message: this.$t('m.File_size_mb'),
            type: 'warning',
            duration: 3000
          })
        }, 0)
        return false
      }
      let isJPG = this.adsDetail.fileType == 1 ? isJPG1 : isJPG2
      // console.log(isJPG, isJPG1, isJPG2, file.type)
      if (!isJPG) {
        setTimeout(() => {
          this.$notify({
            title: file.name + ' ' + this.$t('m.Upload_failed'),
            message: this.$t('m.Incorrect_file_format'),
            type: 'warning',
            duration: 3000
          })
        }, 0)
        return false
      }
      this.$openLoading()
      return true
    },
    //图片/视频改变
    changeList (file, fileList) {
      // console.log(file.raw)
      const isLt20M = file.raw.size / 1024 / 1024 < 20
      const isJPG1 =
        file.raw.type === 'image/jpeg' ||
        file.raw.type === 'image/webp' ||
        file.raw.type === 'image/png'
      const isJPG2 = file.raw.type === 'video/mp4'
      if (!isLt20M) {
        setTimeout(() => {
          this.$notify({
            title: file.name + ' ' + this.$t('m.Upload_failed'),
            message: this.$t('m.File_size_mb'),
            type: 'warning',
            duration: 3000
          })
        }, 0)
        return false
      }
      let isJPG = this.adsDetail.fileType == 1 ? isJPG1 : isJPG2
      // console.log(isJPG, isJPG1, isJPG2, file.raw.type)
      if (!isJPG) {
        setTimeout(() => {
          this.$notify({
            title: file.name + ' ' + this.$t('m.Upload_failed'),
            message: this.$t('m.Incorrect_file_format'),
            type: 'warning',
            duration: 3000
          })
        }, 0)
        return false
      }
      this.playType = 2
      let newFile = new FormData()
      newFile.append('file', file.raw)
      if (fileList.length > 1) {
        fileList.splice(0, 1)
        newFile.delete('file')
        newFile.append('file', fileList[0].raw)
      }
      //给图片src赋值
      this.adsDetail.url = URL.createObjectURL(file.raw)
      this.fileList = fileList
      // console.log(this.fileList);
    },
    onSuccess2 (res, file, fileList) {
      this.$closeLoading()
      let resData = res
      this.$message({
        type: resData.code == '0' ? 'success' : 'error',
        message: resData.message
      })
      this.playType = 1
      this.$router.push({ path: '/ads/program' })
    },

    //调起页面
    uploadBtn () {},

    //播放视频
    playVideo (item) {
      this.urlVideo = item
      this.playDialog = true
    },
    //关闭视频
    closePlay () {
      this.playDialog = false
      this.urlVideo = ''
    },

    //编辑广告
    editAds () {
      this.$refs['adsDetail'].validate(valid => {
        if (valid) {
          // this.$openLoading()
          if (this.fileList.length > 0) {
            try {
              this.$refs.upload.submit()
            } catch (error) {
              this.$message.error(error)
            }
          } else {
            this.$api.ad.editADs(this.adsDetail).then(res => {
              // console.log(res.code);
              if (res.code == 0) {
                // this.$closeLoading()
                this.$message.success(res.message)
                this.$router.push({ path: '/ads/program' })
              } else {
                // this.$closeLoading()
                this.$message.error(res.message)
              }
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  padding-bottom: 84px !important;
  ::v-deep .el-form-item__content {
    line-height: initial !important;
  }
}

.page-header {
  width: 1000px !important;
  min-width: initial !important;
  padding: 20px 0 !important;
}
.table-box {
  width: 1000px !important;
  min-width: initial !important;
  background: #ffffff;
  border-radius: 10px;
  padding: 20px !important;
}

.table_top {
  width: 1000px;
  background: #ffffff;
  border-radius: 10px;
  padding: 24px;
  .table_top_input {
    display: flex;
    .table_top_input_div {
      width: 50%;
    }
  }
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
  .top {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .top_box {
      width: 952px;
      height: 44px;
      background: #ececee;
      border-radius: 8px;

      display: flex;
      justify-content: center;
      align-items: center;

      .active {
        background: #ffffff !important;
        color: var(--text-color) !important;
      }

      & > div {
        width: 472px;
        height: 36px;
        border-radius: 4px;
        cursor: pointer;

        font-size: 16px;
        font-weight: 600;
        text-align: center;
        color: #646b80;
        line-height: 36px;
      }
    }
  }
  .actives {
    padding: 24px 203px 0 203px !important;
  }
  .top_img {
    padding: 24px 106px 0 106px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .top_img_div {
      width: 160px;

      .img_div {
        display: flex;
        justify-content: center;
        width: 160px;
        height: 174px;
        margin-bottom: 20px;
        img {
          width: 160px;
          height: 174px;
        }
      }

      .img_text {
        width: 160px;
        font-size: 12px;
        font-weight: Medium;
        text-align: center;
        color: #66666b;
        line-height: 14px;
      }
    }
  }

  .top_dot {
    display: flex;
    width: 100%;
    align-self: center;
    justify-content: center;
    margin: 20px 0;
    span {
      width: 6px;
      height: 6px;
      background: #d2d8e2;
      border-radius: 3px;
      cursor: pointer;
    }
    .active1 {
      background: #39404d !important;
    }
  }
}
.el_uploaded2 {
  display: flex;
  align-items: center;
  margin: 20px 0;
  .el_uploaded_img {
    width: 466px;
    height: 200px;
    background: #f5f5f7;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    position: relative;
    .image_vertical {
      max-width: 256px;
      height: 160px;
      border-radius: 2px;
    }
    .video_img {
      position: absolute;
      width: 20px;
      height: 20px;
      cursor: pointer;
      z-index: 99;
    }
  }
  .el_button {
    padding: 10px;
    min-width: 116px;
    background: #ffffff !important;
    border: 1px solid #d2d8e2 !important;
    border-radius: 4px;
    color: var(--text-color);
    font-size: 14px;
    font-weight: 500;
    text-align: center;
  }
}

@media screen and (min-width: 1332px) {
  .container {
    display: flex;
    justify-content: center;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
  }
}
</style>
